import express from 'express';
import { checkSchema, validationResult } from 'express-validator'  
import util from 'utility'
import jwt from 'jsonwebtoken';  

const router = express.Router();




// 新增
router.post('/add', checkSchema({
    name:{ notEmpty: true, errorMessage: 'path不能为空' },

}), async(req,res)=>{
    res.validator();  // 对于请求参数进行校验
    
    const { path,actions,pid ,name} = req.body;
    const addData = {
        name
    }
    if(actions) addData.actions = actions;
    if(pid) addData.pid = pid
    if(name) addData.name = name

    await req.prisma.roles.create({
        data: addData
    })
    res.success('新增完成')
})

// 删除abc

router.post('/del',checkSchema({
    id:{ notEmpty: true, errorMessage: 'id不能为空' },
}), async (req,res)=>{
    const { id } = req.body;
    await req.prisma.roles.delete({
        where:{
            id: Number(id)
        }
    })
    res.success('删除成功')
})

// 修改
router.post('/update', checkSchema({
    
    id:{ notEmpty: true, errorMessage: 'id不能为空' },


}), async(req,res)=>{
    res.validator();  // 对于请求参数进行校验
    
    const { path,actions,pid ,name ,id} = req.body;
    const updateData = {}
    if(path) updateData.path = path
    if(actions) updateData.actions = actions
    if(pid) updateData.pid = pid;
    if(name) updateData.name = name
 
   
    await req.prisma.roles.update({
        where:{
            id: Number(id)
        },
        data:updateData
    })
    res.success('修改')
})


//  查一个
router.post('/getone',checkSchema({
    id:{ notEmpty: true, errorMessage: 'id不能为空' },
}), async (req,res)=>{
    const { id } = req.body;
    const info = await req.prisma.roles.findFirst({
        where:{
            id: Number(id)
        }
    })
    res.success(info)
})


router.post('/list', async (req,res)=>{
    const { page =1,limit= 100 } = req.body;
    const list = await req.prisma.roles.findMany({
        take: Number(limit),
        skip: (Number(page) -1 )* Number(limit)
    })
    const count = await req.prisma.roles.count();
    res.success({
        list,
        count
    })
})


router.post('/getListByIds', async (req,res)=>{
    const { roles } = req.body;
    const list = await req.prisma.roles.findMany({
        where:{
            id:{
                in: roles.split(',').map(item=> Number(item))
            }
        }
    })
    res.success(list)
})


export default router;